<template>
	<view class="content">
		<!-- 搜索栏 -->
		<view class="searches">
			<view class="city" @click="selectCity">
				<uni-icons color="#fff" size="22" type="location"></uni-icons>
				<view class="location">{{city}}</view>
			</view>
			<uni-search-bar class="searchbar" radius="5" @confirm="doSearch" @clear="doClear" v-model="searchData.code"
				clearButton="auto" cancelButton="none" placeholder="请输入柜号">
			</uni-search-bar>

			<uni-icons type="scan" size="24" color="#ffffff" @click="doScan()"></uni-icons>
		</view>

		<view class="uni-list option-list">
			<view class="uni-list-cell" v-if="userInfo.type == 'P'">
				<view class="uni-list-cell-left">
					厂商
				</view>
				<view class="uni-list-cell-db">
					<picker @change="orgPickerChange($event, index)" range-key="name" :range="factuer">
						<text v-if="searchData.organizationId">{{organizationName}}</text>
						<text v-else style="color: #999999;">请选择厂商</text>
					</picker>
					<uni-icons v-if="searchData.organizationId" class="close_icon" type="closeempty" size="16"
						color="#ddd" @click="clearOrg"></uni-icons>
				</view>
			</view>
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					运营商
				</view>
				<view class="uni-list-cell-db">
					<picker :disabled="!searchData.organizationId" @change="optPickerChange($event, index)"
						range-key="name" :range="operatorOption">
						<text v-if="searchData.operatorId">{{operatorName}}</text>
						<text v-else style="color: #999999;">{{searchData.organizationId?'请选择运营商':'请先选择厂商'}}</text>
					</picker>
					<uni-icons v-if="searchData.operatorId" class="close_icon" type="closeempty" size="16" color="#ddd"
						@click="clearOpt"></uni-icons>
				</view>
			</view>
			<button type="primary" size="mini" class="search_btn" @click="doSearch">搜索</button>
		</view>

		<uni-card class="card-content" :shadow="false" v-for="(item,index) in dataList" :key="index"
			@click.native="goDetail(item)">
			<template v-slot:title>
				<view class="single">
					<view class="codes">
						<text>{{item.code?item.code:""}}</text>
						<DetectOnline :currentRow="item" @updateStatus="getDataList"></DetectOnline>
					</view>
					<text
						:class="['status',{'isSuccess':item.status===1,'isDelay':item.status===2}]">{{statusData[item.status]}}</text>
				</view>
			</template>
			<view class="address">
				<view class="locate">{{item.address?item.address:""}}</view>
				<view class="caculate" @click.stop="distance(item)" v-if="item.lat&&item.lng">
					<text class="iconfont icon-daohang"></text>
					<text>{{caculateLL(item.lat,item.lng,coord.lat,coord.lng) | toFixed}}</text>
				</view>
			</view>
			<button class="warn-btn" v-if="item.isAlarm === true" plain type="warn" size="mini">故障</button>
			<button class="warn-btn currect-btn" v-if="item.isAlarm === false" plain type="primary"
				size="mini">正常</button>
		</uni-card>

		<view v-show="isLoadMore && dataList.length >0">
			<uni-load-more :status="loadStatus"></uni-load-more>
		</view>

		<view class="nodata" v-if="dataList.length == 0">
			<image class="empty_img" src="/static/images/empty.png" mode="widthFix"></image>
			<view>暂无数据</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
	} from 'vuex';
	import {
		equipment,
		operator
	} from "@/api/my.js";
	import {
		removeNullUndefined,
	} from "@/common/index.js";
	import store from "@/store/index.js";
	import {
		caculateLL,
		getAuthorize
	} from '@/common/index.js';
	import {
		permission
	} from "@/common/permission.js";
	import {
		mapKy,
		AMAP_KEY
	} from "@/common/config.js";
	
	import DetectOnline from "./component/detectOnline.vue";
	export default {
		components:{DetectOnline},
		data() {
			return {
				city: '',
				dataList: [],
				searchData: {
					code: "",
					organizationId: "",
					operatorId: "",
				},
				page: 1, //页码
				size: 8,

				loadStatus: 'loading', //加载样式：more-加载前样式，loading-加载中样式，nomore-没有数据样式
				isLoadMore: false, //是否加载中
				refresh: false, // 下拉刷新标示
				statusData: {},

				organizationName: "",
				operatorOption: [], //运营商option
				operatorName: "",
				caculateLL: caculateLL,
				permission: permission,
				showNoGps: false,
				// coord: {
				// 	lat: '',
				// 	lng: '',
				// },
				statusLoading: false,
			}
		},
		filters: {
			toFixed(str) {
				if (!str) return;
				let count = str > 1000 ? ((str / 1000).toFixed(2) + 'km') : (str.toFixed(2) + 'm');
				return count;
			}
		},
		computed: {
			...mapState(['enums', 'factuer', 'userInfo', 'coord', 'equipTypeCode'])
		},
		watch: {
			enums(val) {
				val.EQUIP_STATUS.forEach(item => {
					this.statusData[item.code] = item.label;
				})
			},
			userInfo(val) {
				if (val.type !== 'P') { //非平台用户
					this.searchData.organizationId = val.organizationId;
					this.getOperator();
				}
			},
			"coord": {
				handler(cur, old) {
					// this.getDataList();

					if (this.coord.lng) {
						this.getCity();
					}
				},
				deep: true, //对象内部的属性监听，也叫深度监听
				immediate: true
			}
		},
		onShow() {
			this.page = 1;
			this.getDataList();
			if (!this.coord.lat) {
				//位置授权
				// getAuthorize()
				// 	//用户允许小程序位置授权
				// 	.then(() => {
				// 		this.getSystemInfo()
				// 	})
				// 	//用户拒绝小程序位置授权
				// 	.catch(() => {
				// 		this.getSystemInfo()
				// 	})
				this.$store.dispatch("updateCoord");
			}
		},
		onLoad() {
			this.$store.dispatch("enumsAll");
			this.$store.dispatch("generatorFactuer");
			this.$store.dispatch("updateUserInfo");
		},

		methods: {
			getDataList() {
				this.$Toast.loading('加载中');
				this.dataList = this.page == 1 ? [] : this.dataList
				equipment('/info/list', 'post', {
						...removeNullUndefined(Object.assign({
							pageNum: this.page,
							pageSize: this.size,
							isAlarm: false,
							equipTypeCode: this.equipTypeCode,
							lat: this.coord.lat,
							lng: this.coord.lng,
						}, this.searchData))
					}).then(res => {
						if (res.code == 200) {
							let datas = res.data;
							this.dataList = this.page == 1 ? datas : this.dataList.concat(datas);

							if (this.dataList.length == +res.total) { //小于size数，停止请求
								this.isLoadMore = true;
								this.loadStatus = 'nomore';
							} else {
								this.isLoadMore = false;
							}
							uni.hideLoading();
							if (this.refresh) {
								uni.stopPullDownRefresh();
								this.refresh = false;
							}
						}
					})
					.catch(error => {
						uni.hideLoading();
						this.isLoadMore = false;
					});

			},
			onPullDownRefresh() {
				this.page = 1;
				this.getDataList();
				this.refresh = true;
			},
			onReachBottom() {
				if (!this.isLoadMore) { //此处判断，上锁，防止重复请求
					this.isLoadMore = true;
					this.page++;
					this.getDataList();
				}
			},
			doSearch() {
				this.page = 1;
				this.getDataList();
			},
			resetSearch() {
				this.resetData();
				this.getDataList();
			},
			// 数据重置
			resetData() {
				this.searchData = {
					code: "",
					organizationId: "",
					operatorId: "",
				};
			},
			doClear() {
				this.searchData.code = "";
				this.page = 1;
				this.getDataList();
			},
			orgPickerChange(e) {
				let index = e.detail.value;
				this.searchData.organizationId = this.factuer[index].id;
				this.organizationName = this.factuer[index].name;

				this.searchData.operatorId = "";
				this.operatorName = "";
				this.operatorOption = [];
				this.getOperator();
			},
			optPickerChange(e) {
				let index = e.detail.value;
				this.searchData.operatorId = this.operatorOption[index].id;
				this.operatorName = this.operatorOption[index].name;
			},
			getOperator() {
				operator(`/all?organizationId=${this.searchData.organizationId}`, 'get').then(res => {
					if (res.code == 200) {
						this.operatorOption = res.data;
					}
				});
			},
			clearOpt() {
				this.searchData.operatorId = "";
				this.operatorName = "";
				this.page = 1;
			},
			clearOrg() {
				this.searchData.organizationId = "";
				this.organizationName = "";
				this.page = 1;
			},
			// 扫码
			doScan() {
				let that = this;
				uni.scanCode({
					onlyFromCamera: true,
					scanType: 'qrCode',
					success: function(res) {
						let str = res.result;
						let index = str.lastIndexOf('/');
						let code = str.substr(index + 1, str.length);
						that.searchData.code = code;
						that.page = 1;
						that.getDataList();
					},
					fail: (err) => {
						this.$Toast.error('扫码失败！');
					}
				});
			},
			// 导航
			distance(item) {
				if (!item.lat || !item.lng) {
					this.$Toast.error('暂无位置信息');
					return;
				}
				uni.openLocation({
					latitude: item.lat, //维度
					longitude: item.lng, //经度
					name: item.code, //目的地定位名称
					scale: 15, //缩放比例
					address: item.address, //导航详细地址
					success: function() {}
				});
			},
			goDetail(item) {
				uni.navigateTo({
					url: `/pages/home/detail?id=${encodeURIComponent(item.id)}&code=${encodeURIComponent(item.code)}&binCount=${item.binCount}`
				})
			},
			selectCity() {
				// if (!this.coord.lat) {
				// 	//位置授权
				// 	getAuthorize()
				// 		//用户允许小程序位置授权
				// 		.then(() => {
				// 			this.getSystemInfo()
				// 		})
				// 		//用户拒绝小程序位置授权
				// 		.catch(() => {
				// 			this.getSystemInfo()
				// 		})
				// 	return;
				// }
				let that = this;
				uni.chooseLocation({
					success: (res) => {
						let datas = res.address;
						store.commit("setCoord", {
							latitude: res.latitude,
							longitude: res.longitude
						});
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			getCity() {
				let that = this;
				let pas = {
					lon: this.coord.lng,
					lat: this.coord.lat,
					ver: 1
				};
				uni.request({
					// header: {
					// 	"Content-Type": "application/text"
					// },
					//注意:这里的key值需要高德地图的 web服务生成的key  只有web服务才有逆地理编码
					url: 'https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=' + this.coord.lng + ',' +
						this.coord
						.lat +
						`&key=${AMAP_KEY}&radius=1000&extensions=all`,
					// 此处为天地图地理位置反编译
					// url: `https://api.tianditu.gov.cn/geocoder?postStr=${JSON.stringify(pas)}&type=geocode&tk=${mapKy}`,
					success(re) {
						if (re.statusCode == 200) {
							// let datas = re.data.result.addressComponent;
							let datas = re.data.regeocode.addressComponent;
							// console.log("获取中文街道地理位置成功", datas)
							that.city = datas.province;
						} else {
							console.log("获取信息失败，请重试！")
						}
					}
				});
			},

			//获取手机系统信息
			getSystemInfo() {
				uni.getSystemInfo({
					success: (res) => {
						// 获取地理位置失败原因
						// 1.手机系统设置中地理位置未开启
						// 2.系统未给微信授权
						// 3.用户未给小程序授权地理位置信息
						if (!res.locationEnabled || !res.locationAuthorized) {
							this.$Toast.none('请确保手机系统定位已开启');
						} else {
							this.getUpdateCoord();
						}
					},
				})
			},
			getUpdateCoord() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						let {
							latitude,
							longitude
						} = res;
						store.commit("setCoord", {
							latitude: res.latitude,
							longitude: res.longitude
						});
					},
					fail: (err) => {
						uni.showModal({
							title: '提示',
							content: '当前定位未开启，请点击“确定”手动开启定位',
							success: (res) => {
								if (res.confirm) {
									// 点击确定引导客户开启定位
									this.openSetting();
								} else if (res.cancel) {
									this.$Toast.none('您拒绝了授权，无法获取位置信息');
								}
							}
						});
					}
				})
			},
			// 4.打开设置
			openSetting() {
				uni.openSetting({
					success: (res) => {
						if (res.authSetting['scope.userLocation']) {
							// 5.用户在设置中点击了允许，调用选择位置信息函数
							// 重新调取uni.getLocation
							this.getUpdateCoord()
						} else {
							// 5.用户在设置中点击了不允许，展示拒绝授权信息
							this.$Toast.none('您拒绝了授权，无法获取位置信息');
						}
					},
					fail: (err) => {
						console.log("打开设置失败", err)
					}
				})
			},
		},
	}
</script>
<style lang="scss">
	page {
		background: #F0F0F0;
	}
</style>
<style lang="scss" scoped>
	@import "@/static/css/common.scss";
	@import "@/static/iconfont.css";

	.content {
		padding-bottom: 20rpx;
	}

	.searches {
		@include flexLayout(center, space-between);
		padding: 20rpx 16rpx 20rpx 10rpx;
		background-color: #51b7b9;
		color: #fff;

		.searchbar {
			width: 72%;
			color: #FFFFFF;
		}

		.city {
			font-size: 24rpx;
			@include flexLayout(center, flex-start);
			align-items: center;

			.location {
				@include exceedFlow(1);
				margin-top: -6rpx;
			}
		}

		/deep/ .uni-searchbar__box {
			background-color: rgba(0, 0, 0, .05) !important;
		}

		/deep/ .uni-searchbar__text-placeholder {
			color: #dddddd;
		}
	}

	.search_btn {
		background-color: #51b7b9;
		margin: 0;
		padding: 0 14rpx;
		font-size: 24rpx;
		position: absolute;
		right: 10rpx;
	}

	button::after {
		border: none;
	}

	/deep/ .uni-searchbar__box {
		height: 64rpx !important;
	}

	/deep/ .uni-card .uni-card__content {
		padding: 0 !important;
	}

	/deep/ .uni-card {
		padding: 20rpx 18rpx !important;
		margin: 14rpx 20rpx !important;
		border-radius: 24rpx;
	}

	/deep/ .uni-searchbar {
		padding: 0 10rpx;
	}

	.card-content {
		.single {
			@include flexLayout(center, space-between);

			.codes {
				@include flexLayout(center, flex-start);

				image {
					margin-left: 10rpx;
				}
			}

			.status {
				font-size: 24rpx;
				color: #666666;
			}

			.isSuccess {
				color: #51b7b9;
			}

			.isDelay {
				color: #e64340;
			}
		}

		.address {
			@include flexLayout(center, space-between);
			margin: 8rpx 0;

			.locate {
				width: 94%;
				@include exceedFlow(1);
			}

			.caculate {
				@include flexLayout(center, flex-start);

			}
		}

		.warn-btn {
			height: 52rpx;
			line-height: 52rpx;
			padding: 0 16rpx;
		}

		.currect-btn {
			color: #51b7b9;
			border-color: #51b7b9;
		}
	}

	.option-list {
		line-height: 80rpx;
		font-size: 28rpx;
		color: #333333;
		padding: 0 40rpx;
		@include flexLayout(center, flex-start);
		background: #fff;

		.uni-list-cell {
			@include flexLayout(center, flex-start);

			// border-bottom: 2rpx solid #efefef;
			.uni-list-cell-left {
				color: #000;
			}

			.uni-list-cell-db {
				margin-left: 10rpx;

				@include flexLayout(center, flex-start);

				picker {
					color: #333333;
					max-width: 200rpx;
					@include exceedFlow(1);
				}
			}
		}

		.uni-list-cell:first-child {
			margin-right: 10rpx;
		}
	}

	.icon-daohang {
		color: #51b7b9;
		font-size: 32rpx;
		margin-bottom: -4rpx;
		margin-right: 6rpx;
	}
</style>